package com.mt.api.core.config.interceptor;

import com.mt.common.utils.RedisUtils;
import com.mt.api.core.annotation.RepeatReqValid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: plover
 * @Date: 2020/08/08/10:20 上午
 * @Description:
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Order(1)
public class RepeatReqHandlerIntreceptor implements HandlerInterceptor {

    private final RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            ServletInputStream inputStream = request.getInputStream();
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                RepeatReqValid methodAnnotation = handlerMethod.getMethodAnnotation(RepeatReqValid.class);
                if (Objects.nonNull(methodAnnotation) && methodAnnotation.value()) {
                    String body = IOUtils.toString(inputStream, "utf-8");
                    String md5Body = DigestUtils.md5Hex(body);
                    if (redisUtils.hasKey(md5Body)) {
                        log.info("请求方法:{},请求参数重复：{}", request.getRequestURL(), body);
                        return false;
                    } else {
                        redisUtils.set(md5Body, body, 10);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}
